package cn.huiyunche.driver.controller;

import cn.huiyunche.base.service.constant.RegularConstant;
import cn.huiyunche.base.service.enums.EnabledEnum;
import cn.huiyunche.base.service.enums.UserTypeEnum;
import cn.huiyunche.base.service.framework.security.JwtAuthenicationFilter;
import cn.huiyunche.base.service.framework.security.JwtUtils;
import cn.huiyunche.base.service.framework.utils.UserAgentUtils;
import cn.huiyunche.base.service.interfaces.SendMessageService;
import cn.huiyunche.base.service.interfaces.UserService;
import cn.huiyunche.base.service.model.SUser;
import cn.huiyunche.base.service.vo.Result;
import cn.huiyunche.base.service.vo.SignUpVo;
import cn.huiyunche.base.service.vo.UserVo;
import cn.huiyunche.tools.basic.exceptions.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/sign")
public class SignUpController {
    private static final Logger LOGGER = LoggerFactory.getLogger(SignUpController.class);

    @Autowired
    private UserService userService = null;

    @Autowired
    private SendMessageService sendService = null;

    @Value("#{configProperties['secure.key']}")
    private String securrKey;

    private String getSecurrKey() {
        return this.securrKey;
    }

    private SendMessageService getSendMessageService() {
        return this.sendService;
    }

    private UserService getUserService() {
        return this.userService;
    }

    /**
     * @return
     * @Title:
     * @Description: 注册
     * @return: Result<String>
     */
    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public Result<Object> signUp(HttpServletRequest request, @Valid SignUpVo vo, BindingResult br) throws BusinessException {
        LOGGER.info("SignController.signUp params : {}, {}, {}, {}, {}, {}, {}", vo.getPhone(), vo.getCode(), vo.getOpenid(), vo.getUuid(), vo.getUsertype(), vo.getPassword(), vo.getInvitedcode());
        Result<Object> result = new Result<Object>(true, "注册成功!");
        if (br.hasErrors()) {
            List<ObjectError> list = br.getAllErrors();
            result.setSuccess(false);
            result.setMessage(list.get(0).getDefaultMessage());
            return result;
        }
        if (StringUtils.isBlank(vo.getOpenid()) && StringUtils.isBlank(vo.getUuid())) {
            throw new BusinessException("openid或uuid不能为空");
        } else if (vo.getPassword().length() > 14) {
            throw new BusinessException("密码长度为6-14位");
        } else if (vo.getPassword().length() < 6) {
            throw new BusinessException("密码长度为6-14位");
        } else if (!vo.getPassword().matches(RegularConstant.reg)) {
            throw new BusinessException("密码必须是数字和字母组合");
        }
        // 获取redis中存储的验证码和用户输入的验证码比较
        String authCode = null;
        try {
            authCode = this.getUserService().getAuthCode(vo.getPhone(), Integer.valueOf(vo.getUsertype()));
            if (vo.getCode().equals(authCode)) {
                SUser up = this.getUserService().getByPhone(vo.getPhone(), Arrays.asList(UserTypeEnum.SEND_DRIVER.getValue(), UserTypeEnum.CONSUMER_DRIVER.getValue()));
                if (up != null) {
                    LOGGER.error("SignUpController.signUp error : This user already exists {}", vo.getPhone());
                    throw new BusinessException("此用户已存在!");
                }
                // 区分请求设备类型
                String deviceType = UserAgentUtils.getDeviceType(request).getName();
                // 添加用户
                Long flag = this.getUserService().add(vo.getPhone(), vo.getOpenid(), vo.getUuid(), deviceType,
                        Integer.valueOf(vo.getUsertype()), vo.getPassword(), vo.getInvitedcode());
                SUser user = this.getUserService().getById((long) flag);
                UserVo uv = new UserVo(user.getId(), user.getPhone(), user.getPwd(), user.getOpenId(),
                        user.getEnable().equals(EnabledEnum.T.getValue()) ? true : false, user.getUserType());
                String token = JwtUtils.generateToken(uv, this.getSecurrKey());
                HashMap<String, String> map = new HashMap<String, String>();
                map.put(JwtAuthenicationFilter.HEADER_AUTHORIZATION, JwtAuthenicationFilter.PREFIX_AUTHORIZATION + token);
                result.setData(map);

                //验证正确，移除redis中的验证码
                userService.removeAuthcode(vo.getPhone() + vo.getUsertype());

            } else {
                result.setSuccess(false);
                result.setMessage("验证码错误!");
            }
        } catch (Exception e1) {
            LOGGER.error("SignUpController.signUp error : {}", e1);
            throw new BusinessException("系统错误！");
        }
        return result;
    }

    /**
     * @param phone    手机号
     * @param usertype 用户类型（10为司机 20为货主，30为运输公司，40为托运企业，50为人送车）
     * @return
     * @Title: sendAuthCode
     * @Description: 注册发送验证码
     * @return: Result<String>
     */
    @RequestMapping(value = "/captcha", method = RequestMethod.POST)
    @ResponseBody
    public Result<String> sendCaptcha(@RequestParam("phone") String phone, @RequestParam("usertype") int usertype) {
        LOGGER.info("SignController.sendAuthCode params : {}, {}", phone, usertype);
        Result<String> result = new Result<String>(true, "发送成功！");
        if (StringUtils.isBlank(phone)) {
            LOGGER.info("sendAuthCode{}", phone);
            throw new BusinessException("手机号不能为空!");
        }
        // 判断用户是否注册
        SUser uesr = this.getUserService().getByPhone(phone, Arrays.asList(UserTypeEnum.SEND_DRIVER.getValue(), UserTypeEnum.CONSUMER_DRIVER.getValue()));
        if (uesr != null) {
            throw new BusinessException("用户已注册！");
        }
        // 发送验证码
        result.setMessage(this.getSendMessageService().sendCaptcha(phone, usertype));
        return result;
    }


}
